from flask import render_template, Blueprint, request

from apps.pojo.Entity import User, UserSchema, db

from apps.util.LayData import LayData
user_bp = Blueprint('user', __name__, url_prefix='/user')
user_schema = UserSchema(many=True)
@user_bp.route('/tolist')
def tolist():
    return render_template('user/list.html')


@user_bp.route('/list', methods=['POST', 'GET'])
def list():
    # 接收分页参数 page 当前页 limit 每页条数
    page = request.args.get('page', 1, type=int)
    limit = request.args.get('limit', 10, type=int)

    count = User.query.count()

    userlist = User.query.offset((page - 1) * limit).limit(limit).all()
    users = user_schema.dump(userlist)


    return {
        'code': 0,
        'msg': '查询成功',
        'count': count,
        'data': users
    }


@user_bp.route('/toadd')
def toadd():
    return render_template('user/add.html')

@user_bp.route('/add', methods=['POST'])
def addSave():

    user = User()
    user.username = request.form['username']
    user.password = request.form['password']
    user.sex = request.form['sex']
    try:
        db.session.add(user)
        db.session.commit()
        return LayData.data2(200, '添加成功')
    except Exception as e:
        db.session.rollback()
        return LayData.data2(500, '添加失败')


@user_bp.route('/toUpdate/<int:id>')
def toEidt(id):

    user = User.query.filter(User.id == id).first()
    return render_template('user/edit.html', user=user)


@user_bp.route('/delete', methods=['POST'])
def delete():
    data = request.get_json()
    ids = data.get('ids', [])

    try:
        deleted_count = User.query.filter(User.id.in_(ids)).delete(synchronize_session=False)
        db.session.commit()
        return LayData.data2(200, '删除成功')
    except Exception as e:
        db.session.rollback()
        return LayData.data2(500, '删除失败')

@user_bp.route('/update', methods=['POST'])
def update():
    id = request.form['id']
    user = User.query.filter(User.id == id).first()
    if user is None:
        return "用户不存在", 404

    user.username = request.form['username']
    user.password = request.form['password']
    user.sex = request.form['sex']

    try:

        db.session.commit()
        return LayData.data2(200, '更新成功')
    except Exception as e:
        db.session.rollback()
        return LayData.data2(500, '更新失败')
